package com.feixiang.springbootinit.wechat;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feixiang.springbootinit.constant.WxConstant;
import com.feixiang.springbootinit.model.entity.wechat.NmSubscribers;
import com.feixiang.springbootinit.service.NmSubscribersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service

/**
 * 企微相关接口对接
 * https://developer.work.weixin.qq.com/document/path/94867
 */
public class WeComApi {
    @Resource
    private NmSubscribersService nmSubscribersService;
    // 使用本地缓存
    private static String token = null;
    private static Date expireTime = null;
    // 企微获取 token 的 URL
    private static final String accessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET";
    //撤回应用消息
    private static final String recallMessageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/recall?access_token=ACCESS_TOKEN";
    //批量获取客户详情
    private static final String getCustomerDetailUrl = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token=ACCESS_TOKEN";
    //获取客户列表
    private static final String getCustomerListUrl = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token=ACCESS_TOKEN&userid=USERID";
    // 如果需要代理，可配置以下字段
    private static final String httpProxyHost = null; // 可删除或设为空值
    private static final int httpProxyPort = 0;       // 可删除或设为空值

    /**
     * 获取企业微信的 access_token
     *
     * @param corpId  企业的唯一标识 ID
     * @param agentId 应用的密钥凭证
     * @return access_token 字符串
     */
    public String getToken(String corpId, String agentId) {
        try {
            log.info("获取access_token开始......");
            // 判断当前 token 是否有效
            if (token != null && expireTime != null && new Date().before(expireTime)) { //TODO 使用高效的缓存方式
                log.info("使用本地内存缓存的：access_token:{}", token);
                return token;
            }
            // 构建请求URL
            String requestUrl = accessTokenUrl.replace("ID", corpId).replace("SECRET", agentId.trim());
            log.info("请求URL:{}", requestUrl);
            // 发起HTTP请求
            String result;
            if (httpProxyHost != null && httpProxyPort > 0) {
                result = HttpRequest.get(requestUrl).setHttpProxy(httpProxyHost, httpProxyPort).execute().body();
            } else {
                result = HttpRequest.get(requestUrl).execute().body();
            }
            log.info("从企微获取access_token结果:{}", result);
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if (jsonObject != null && jsonObject.containsKey("access_token")) {
                token = jsonObject.getStr("access_token");
                int expiresIn = jsonObject.getInt("expires_in");
                // 设置过期时间（默认有效期为 7200 秒）
                expireTime = new Date(System.currentTimeMillis() + expiresIn * 1000L);
                log.info("更新access_token，有效期至：{}", DateUtil.format(expireTime, "yyyy-MM-dd HH:mm:ss"));
            } else {
                log.warn("企微返回中未包含有效的 access_token，原始响应：{}", result);
                token = null; // 清除无效token
            }
        } catch (Exception e) {
            log.error("获取token失败: {}", e.getMessage(), e);
            token = null; // 出现异常时清除token以确保下次重新拉取
        }
        return token;
    }
    /**
     * 获取JCH项目企业微信的 access_token
     *
     * @param corpId  企业的唯一标识 ID
     * @param agentId 应用的密钥凭证
     * @return access_token 字符串
     */
    /**
     *  撤回应用消息
     */
    public String recallMessage(String msgId) {
        // 构建请求URL
        String requestUrl = recallMessageUrl.replace("ACCESS_TOKEN", token.trim());
        log.info("请求URL:{}", requestUrl);
        // 发起HTTP请求
        String result = HttpRequest.get(requestUrl).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject != null && jsonObject.getInt("errcode") == 0) {
            log.info("撤回应用消息成功");
            return "success";

        } else {
            log.warn("撤回应用消息失败: {}", jsonObject.getStr("errmsg"));
            return "error";
    }
    }
    /**
     * 获取客户列表
     */
    public List<String> getCustomerList() {
        // 构建请求URL
        String requestUrl = getCustomerListUrl.replace("ACCESS_TOKEN", token.trim()).replace("USERID", "FeiXiang");
        log.info("请求URL:{}", requestUrl);
        // 发起HTTP请求
        String result = HttpRequest.get(requestUrl).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject != null && jsonObject.getInt("errcode") == 0) {
            log.info("获取客户列表成功：{}", jsonObject);
            List<String> externalUserIdList = jsonObject.getJSONArray("external_userid").toList(String.class);
            log.info("获取客外部联系人集合列表：{}", externalUserIdList);
            return externalUserIdList;
        } else {
            log.warn("获取客户列表失败: {}", jsonObject);
            return null;
    }
    }

    /**
     * 批量获取客户详情
     */
    public String getCustomerDetail(String cursor, Integer limit) {
        // 构建请求URL
        String requestUrl = getCustomerDetailUrl.replace("ACCESS_TOKEN", token.trim());
        log.info("请求URL:{}", requestUrl);
        // 构建请求参数
        JSONObject requestBody = new JSONObject();
        // 设置userid_list数组
        JSONArray useridList = new JSONArray();
        useridList.add("FeiXiang");
        requestBody.put("userid_list", useridList);
        // 设置可选参数cursor
        if (cursor != null && !cursor.isEmpty()) {
            requestBody.put("cursor", cursor);
        }
        // 设置可选参数limit，确保不超过最大值100
        if (limit != null) {
            requestBody.put("limit", Math.min(limit, 100));
        } else {
            // 默认值
            requestBody.put("limit", 50);
        }
        // 发起HTTP请求
        String result = HttpRequest.post(requestUrl).body(requestBody.toString()).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject != null && jsonObject.getInt("errcode") == 0) {
            log.info("批量获取客户详情成功：{}", jsonObject);
            List<String> externalContactList = jsonObject.getJSONArray("external_contact_list").toList(String.class);
            log.info("获取外部联系人集合列表：{}", externalContactList);
            //打印每一个外部联系人的详细信息
            for (String externalContact : externalContactList) {
                JSONObject externalContactJson = JSONUtil.parseObj(externalContact);
                log.info("获取外部联系人详细信息：{}", externalContactJson);
                /**
                 * {"follow_info":{"userid":"FeiXiang","remark":"福星","description":"","createtime":1752204523,"tag_id":[],"remark_mobiles":[],"add_way":1,"oper_userid":"FeiXiang"},"external_contact":{"external_userid":"wmSDKwCwAA8aOigr3frC4UhdAdMBL-Nw","name":"福星","type":1,"avatar":"http://wx.qlogo.cn/mmhead/qd3u5IHSYT8D8GsIFibhctu1pBRnQekYP0moAOrkDVAkQdAsQG3UegA/0","gender":1}}
                 */
                //获取 remark
                JSONObject follow_info = externalContactJson.getJSONObject("follow_info");
                JSONObject external_contact = externalContactJson.getJSONObject("external_contact");
                String remark = follow_info.getStr("remark");
                log.info("获取外部联系人备注：{}", remark);
                //将备注添加到数据库中描述中
                log.info("更新外部联系人:{},将联系人备注写到表的描述中:描述为{}", external_contact.getStr("external_userid"), remark);
                //获取 external_contact 的  external_userid
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("origid", external_contact.getStr("external_userid"));
                NmSubscribers nmSubscribers = nmSubscribersService.getOne(queryWrapper);
                if (nmSubscribers != null) {
                    nmSubscribers.setNote(remark);
                    nmSubscribersService.update(nmSubscribers, queryWrapper);
                }
            }
            return "success";
        } else {
            log.warn("批量获取客户详情失败: {}", jsonObject);
            return "error";
        }
    }


}
